#!/usr/bin/perl
##################################################################################
# Copyright (C) 2010  Chris Rutledge <rutledge.chris@gmail.com>
#
# http://code.google.com/p/apsh
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
##################################################################################
use strict;
use lib "/usr/local/lib/perl";
use APSH;

##############################
# Error checking
##############################
if (! $ARGV[0] || ! $ARGV[1]){
   print STDERR "Usage: apsh <NODEORGROUP[,NODEORGROUP[,..]]> <CMD>\n";

   if($ARGV[0]){
      print STDERR "\nERROR: no command to run!\n";
   }

   exit(1);
}

##############################
# Global Variables
##############################
my @NODES      = APSH::GenNodes($ARGV[0]);
my $CMD        = APSH::QuoteCMD($ARGV[1]);

APSH::CreateThreads(@NODES);

##############################
# RunCMD()
#
# Get $HOST and $USER from string
# passed and run the command.
##############################
sub RunCMD {
   my $NODECFG = shift;

   $APSH::THREADCNT++;

   open(FH, "ssh -o LogLevel=Error -o BatchMode=yes $NODECFG->{'SSH_OPTS'} -l $NODECFG->{'USERNAME'} $NODECFG->{'HOSTNAME'} $CMD 2>&1 |");

   while(<FH>){
      $APSH::QUEUE->enqueue("$NODECFG->{'HOSTNAME'}: $NODECFG->{'PADDING'}$_");
   }

   close(FH);

   $APSH::QUEUE->enqueue("--THREAD_FINISHED--");
}
